//
//  JSONRPCService.m
//  WorldCupResource
//
//  Created by Kyaw Phyu Aung on 24.4.10..
//  Copyright 2010 Dizzey.com. All rights reserved.
//

#import "JSONRPCService.h"
#import "JSON.h"
#import "Park.h"
#import "ParkArea.h"
#import "BBQPit.h"
#import "Customer.h"

@implementation JSONRPCService
@synthesize delegate;

-(id) initWithURL:(NSURL*)serviceURL {
	return [self initWithURL:serviceURL user:nil pass:nil];
}

-(id) initWithURL:(NSURL*)serviceURL user:(NSString*)user pass:(NSString*)pass {
	if (self = [super init]) {
		url = [serviceURL retain];
		username = [user retain];
		password = [pass retain];
	}
	return self;
}


-(NSString*) saveBooking:(NSString*)parkName andPitName:(NSString*)pitName andCustomerName:(NSString*)customerName andCustomerNRIC:(NSString*)customerNRIC{
	
	NSString *urlString = [NSString stringWithFormat:@"http://aspspider.ws/zirano/Service.svc/SaveBooking?ParkName=%@&PitName=%@&CustomerName=%@&CustomerNRIC=%@",parkName,pitName,customerName,customerNRIC];
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *getURL = [NSURL URLWithString:urlString];
	NSString *responseString = [self execGetMethod:getURL];
	return responseString;
}

//Post Data
-(void) execPostMethod{
	
	Customer *cust = [[Customer alloc] init];
	NSString* reqString = [NSString stringWithString:[cust JSONRepresentation]];
	
	//Request
	NSURL *postURL = [NSURL URLWithString:@"http://aspspider.ws/zirano/Service.svc/SaveCustomer"];
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:postURL];
	NSData* requestData = [NSData dataWithBytes:[reqString UTF8String] length:[reqString length]];
	
	//prepare http body
	[request setHTTPMethod: @"POST"];
	[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
	[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody: requestData];
	
	NSError			*requestError;
	NSURLResponse	*urlResponse;
	NSError			*error = nil;
	NSString *responseString = nil;
	
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request
												 returningResponse:&urlResponse 
															 error:&requestError];
	if (error == nil) {
		if ([urlResponse isKindOfClass:[NSHTTPURLResponse class]]) {
			NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
			int status = [httpResponse statusCode];
			// if the call was okay, then invoke the parser
			if ((status >= 200) && (status < 300)) {
				responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
				//[responseString release];
			}
		}
	}
	[cust release];
	[responseString release];
	[request release];
}

//Get Data
-(NSString*) execGetMethod:(NSURL*)getURL {
	
	NSString *responseString = nil;
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = YES;

	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:getURL];
	[request setHTTPMethod:@"GET"];
	
	NSError			*requestError;
	NSURLResponse	*urlResponse;
	NSError			*error = nil;
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request
												 returningResponse:&urlResponse 
															 error:&requestError];
	if (error == nil) {
		if ([urlResponse isKindOfClass:[NSHTTPURLResponse class]]) {
			NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) urlResponse;
			int status = [httpResponse statusCode];
			// if the call was okay, then invoke the parser
			if ((status >= 200) && (status < 300)) {
				responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
				//[responseString release];
			}
		}
	}

	[request release];
	return [responseString autorelease];
}

-(NSMutableArray*) getAllParks{

	NSURL *getURL = [NSURL URLWithString:@"http://aspspider.ws/zirano/Service.svc/GetAllParks"];
	NSString *responseString = [self execGetMethod:getURL];
	NSMutableArray* items = [(NSDictionary*)[responseString JSONValue] objectForKey:@"Parks"];
	
	NSMutableArray *parkList = [[NSMutableArray alloc] init];
	ParkArea *parkArea = nil;
	NSString *name = nil;
	NSString *address = nil;
	NSString *postalCode = nil;

	for (NSMutableDictionary *loan in items){
		//fetch the data
		name = [loan objectForKey:@"ParkName"];
		address = [loan objectForKey:@"ParkAddress"];
		postalCode = [loan objectForKey:@"ParkPostalCode"];
	
		parkArea = [[ParkArea alloc] init];
		parkArea.park.parkName = name;
		parkArea.park.parkAddress = address;
		parkArea.park.postalCode = postalCode;
	
		[parkList addObject:parkArea];
		[parkArea release];
	}
	
	return [parkList autorelease];
}


-(NSMutableArray*) getPitsByParkAndArea:(NSString*)parkName andParkArea:(NSString*)parkAreaName{
	NSMutableArray *retPits = [[NSMutableArray alloc] init];
	
	NSString *urlString = [NSString stringWithFormat:@"http://aspspider.ws/zirano/Service.svc/GetBBQPitsList?ParkName=%@&ParkAreaName=%@",parkName,parkAreaName];
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSURL *getURL = [NSURL URLWithString:urlString];
	NSString *responseString = [self execGetMethod:getURL];
	
	NSMutableArray* items = [(NSDictionary*)[responseString JSONValue] objectForKey:@"Pits"];
	
	BBQPit *pit = nil;
	for (NSMutableDictionary *loan in items){
	
		//fetch the data
		NSString* name = [loan objectForKey:@"PitName"];
		NSString *price = [loan objectForKey:@"Price"];
		NSString *status = [loan objectForKey:@"Status"];
	
		pit = [[BBQPit alloc] init];
		pit.status = status;
		pit.assignedPitName = name;
		pit.price = [price floatValue];
		
		[retPits addObject:pit];
		[pit release];
	}
	
	//NSLog(@"%i",[retPits count]);
	
	
	return [retPits autorelease];
}

-(NSMutableArray*) getAllParkAreas:(NSString *)parkName{
	NSMutableArray *retParkAreas = [[NSMutableArray alloc] init];;
	NSString* name = nil;

	NSString *urlString = [NSString stringWithFormat:@"http://aspspider.ws/zirano/Service.svc/GetParkAreas?ParkName=%@",parkName];
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	NSURL *getURL = [NSURL URLWithString:urlString];
	NSString *responseString = [self execGetMethod:getURL];
	
	//NSLog(@"%@",responseString);

	NSMutableArray* items = [(NSDictionary*)[responseString JSONValue] objectForKey:@"ParkAreas"];
	
	for (NSMutableDictionary *loan in items){
		//fetch the data
		name = [loan objectForKey:@"AreaName"];
		[retParkAreas addObject:name];
	}
	return [retParkAreas autorelease];
}

-(void) cancelRequest {
	
	if (urlConnection) {
		[urlConnection cancel];
		[urlConnection release];
		urlConnection = nil;
		[webData release];
		webData = nil;
	}
	
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
}

#pragma mark -
#pragma mark NSURLConnection delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	NSLog(@"Did receive response: %@", response);
	
	[webData release];
	webData = [[NSMutableData alloc] init];
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	assert(webData != nil);
	[webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[webData release];
	webData = nil;
	[urlConnection release];
	urlConnection = nil;
	
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
	
	//notify
	[delegate loadingFailed:[error localizedDescription]];
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[urlConnection release];
	urlConnection = nil;
	
	UIApplication* app = [UIApplication sharedApplication];
	app.networkActivityIndicatorVisible = NO;
	
	//DO something with webData
	[delegate dataLoaded:webData];
	
	[webData release];
	webData = nil;
}

-(void) dealloc {
	[webData release];
	[username release];
	[password release];
	[urlConnection release];
	[url release];
	[super dealloc];
}
@end
